import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:palette_generator/palette_generator.dart';
import 'package:url_launcher/url_launcher.dart';

import 'toast_util.dart';

class Utils {
  /// 获取运行平台是Android还是IOS
  static bool get isAndroid => Platform.isAndroid;

  static bool get isIOS => Platform.isIOS;

  /// 是否是生产环境
  // static bool inProduction = const bool.fromEnvironment("dart.vm.product");
  static const bool inProduction = kReleaseMode;

  /// 文字转颜色
  static Color strToColor(String name) {
    assert(name.length > 1);
    final int hash = name.hashCode & 0xffff;
    final double hue = (360.0 * hash / (1 << 15)) % 360.0;
    return HSVColor.fromAHSV(1.0, hue, 0.4, 0.90).toColor();
  }

  /// 随机颜色
  static Color randomColor() {
    return Color.fromARGB(255, Random().nextInt(255), Random().nextInt(255),
        Random().nextInt(255));
  }

  static updateStatusBarStyle(SystemUiOverlayStyle style) {
    SystemChrome.setSystemUIOverlayStyle(style);
  }

  /// 复制到剪粘板
  static copyToClipboard(final String text) {
    Clipboard.setData(new ClipboardData(text: text));
  }

  static Future<Color> getImageLightVibrantColor(String imagePath,
      {Color defaultColor = Colors.white30, String type = "network"}) async {
    PaletteGenerator paletteGenerator =
        await PaletteGenerator.fromImageProvider(type == "network"
            ? NetworkImage(imagePath)
            : Image.asset(imagePath) as ImageProvider<Object>);

    return paletteGenerator.lightVibrantColor?.color ?? defaultColor;
  }

  static Future<Color> getImageDominantColor(String imagePath,
      {Color defaultColor = Colors.blueAccent, String type = "network"}) async {
    PaletteGenerator paletteGenerator =
        await PaletteGenerator.fromImageProvider((type == "network"
            ? NetworkImage(imagePath)
            : AssetImage(imagePath)) as ImageProvider<Object>);

    return paletteGenerator.dominantColor?.color ?? defaultColor;
  }

  static Future<Color> getImageDarkMutedColor(String imagePath,
      {Color defaultColor = Colors.blueAccent, String type = "network"}) async {
    PaletteGenerator paletteGenerator =
        await PaletteGenerator.fromImageProvider(type == "network"
            ? NetworkImage(imagePath)
            : Image.asset(imagePath) as ImageProvider<Object>);

    return paletteGenerator.darkMutedColor?.color ?? defaultColor;
  }

  static void launchURL(String url) {
    Uri uri = Uri.parse(url);
    canLaunchUrl(uri).then((value) {
      if (value) {
        launchUrl(uri);
      } else {
        Toast.showWarn("无效的链接");
      }
    });
  }

  /// 验证格式是否为邮箱
  static bool isEmail(String email) {
    RegExp exp =
        RegExp("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\$");
    return exp.hasMatch(email);
  }

  /// 验证格式是否为手机
  static bool isPhone(String phone) {
    RegExp exp = RegExp(
        r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
    return exp.hasMatch(phone);
  }

  /// 默认在200毫秒内防止重复触发点击事件
  ///
  /// [fn] 点击事件
  ///
  /// [duration] 时间间隔差(毫秒)
  static Function debounce(Function fn, [int duration = 200]) {
    Timer? _debounce;
    return () {
      // 还在时间之内，抛弃上一次
      if (_debounce?.isActive ?? false) _debounce!.cancel();
      _debounce = Timer(Duration(milliseconds: duration), () {
        fn();
      });
    };
  }

  /// 震动反馈
  static void feedbackVibrate() async {
    HapticFeedback.lightImpact();
  }
}
